import Api from '../api'

const LOCAL_USER_INFO = 'LOCAL_USER_INFO';
const LOCAL_USER_TYPE = 'LOCAL_USER_TYPE';

export default {
  // 获取站点信息
  getSite:function(site){
    return {};
  },
  // 判断
  requestUser:function(type, successFn, failFn) {
    let userData = sessionStorage.getItem(LOCAL_USER_INFO);
    if (userData) {
      if (successFn) successFn(userData);
      this.onChange(userData);
      return true;
    }
    this.ajaxGetUser(type, successFn, failFn);
  },
  ajaxGetUser: function(type, successFn, failFn){
    Api.getUser({type})
    .then(
      res => {
        sessionStorage.setItem(LOCAL_USER_TYPE, type);
        if(res.errorCode === 200){
          // 有注册信息 保存至本地，保存至location.state，放行
          sessionStorage.setItem(LOCAL_USER_INFO, JSON.stringify(res.data));
        }else if(res.errorCode === 401){
          sessionStorage.removeItem(LOCAL_USER_INFO);
        }
        successFn(res);
      },
      err => {
        failFn(err.message || '登录失败');
      }
    )
  },
  getUser: function () {
    let userData = null;
    try{ userData = JSON.parse(sessionStorage.getItem(LOCAL_USER_INFO)) }catch(e){}
    return userData;
  },
  getType: function(){
    return ~~sessionStorage.getItem(LOCAL_USER_TYPE) || 1;
  },
  clearUser: function (cb) {
    delete sessionStorage.removeItem(LOCAL_USER_INFO)
    if (cb) cb()
    this.onChange(false)
  },
  isResite: function () {
    return !!sessionStorage.getItem(LOCAL_USER_INFO)
  },
  changeUser: function (data){
    if(data){
      sessionStorage.setItem(LOCAL_USER_INFO, JSON.stringify(data));
    }else{
      sessionStorage.setItem(LOCAL_USER_INFO, '');
    }
  }
}
